package dsk.demo.miaosha.demo.rabbitmq;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import dsk.demo.miaosha.demo.mapper.OrderMapper;
import dsk.demo.miaosha.demo.pojo.Order;
import dsk.demo.miaosha.demo.pojo.SeckillGoods;
import dsk.demo.miaosha.demo.pojo.SeckillOrder;
import dsk.demo.miaosha.demo.pojo.User;
import dsk.demo.miaosha.demo.service.IGoodsService;
import dsk.demo.miaosha.demo.service.IOrderService;
import dsk.demo.miaosha.demo.service.ISeckillGoodsService;
import dsk.demo.miaosha.demo.service.ISeckillOrderService;
import dsk.demo.miaosha.demo.vo.GoodsVo;
import dsk.demo.miaosha.demo.vo.RespBean;
import dsk.demo.miaosha.demo.vo.RespBeanEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;

@Service
@Slf4j
public class MQReceiver {
    @Autowired
    IGoodsService goodsService;

    @Autowired
    private ISeckillGoodsService seckillGoodsService;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private IOrderService orderService;

    @Autowired
    private RedisTemplate redisTemplate;

    @RabbitListener(queues = "seckillQueue")
    public void receive(SeckillMessage msg){
        log.info("接受消息" + msg.toString());
        User user = msg.getUser();
        Long goodsId = msg.getGoodsId();
        GoodsVo goods = goodsService.findGoodsVoById(goodsId);
        if(goods.getStockCount() < 1){
            return;
        }
        //判断是否重复抢购
        String seckillOrder =(String) redisTemplate.opsForValue().get("order:" + user.getId() + ":" + goodsId);
        if(!StringUtils.isEmpty(seckillOrder)) {
            return ;
        }

        orderService.seckill(user,goods);
    }
}
